<template>
	<view>
		<!-- <u-navbar :is-back="true" :is-fixed="true" title="编辑上游订单"></u-navbar> -->
		<scroll-view scroll-y scroll-with-animation style="height: calc(100vh - 60px);" :show-scrollbar="false">
			<view>
				<view style=" background-color:#EFEDE9;">
					<view class="pl-2 pr-2 font-14 lineHight-40 font-weight-bold">服务信息</view>
				</view>
				<view class="pl-3 pr-2">
					<u-form :model="form" ref="uForm">
						<!-- <u-form-item required label-width="180" label="上游服务商" prop="productInformId">
							<u-input @v-model="valueProductName" :value="form.upperEnterpriseName" placeholder="请选择"
								:type="type" input-align="right" :border="false" @click="showProductName = true" />
							<u-action-sheet :list="actionListCp" v-model="showProductName"
								@click="actionClickProductName"></u-action-sheet>
						</u-form-item> -->
						<u-form-item required label-width="180" label="上游服务商" prop="productInformId">
							<u-input @v-model="valueProductName" :value="form.upperEnterpriseName"
								placeholder="请选择上游服务商" :type="type" input-align="right" :border="false"
								@click="showNatureBusinessHandler" />
							<u-picker @confirm="selectNatureBusiness" mode="selector" v-model="showNatureBusiness"
								:default-selector="[0]" :range="natureBusinessList" range-key="text"></u-picker>
						</u-form-item>
						<u-form-item required label-width="200" label="产品/服务名称" prop="productServeName">
							<u-input v-model="form.productServeName" input-align="right" />
						</u-form-item>
						<u-form-item required label-width="180" label="服务商名称" prop="serviceName">
							<u-input v-model="form.serviceName" input-align="right" />
						</u-form-item>
						<u-form-item required label-width="180" label="服务介绍" prop="serviceIntroduce">
							<u-input type="textarea" height="100" v-model="form.serviceIntroduce" input-align="right" />
						</u-form-item>
						<view class="text-right text-BEBFE8">({{ wordCount }} / {{maxCharacters }})</view>
						<u-form-item :required="true" label-width="180" label="服务介绍详情">
							<u-upload ref="uUpload" :file-list="fileList" :max-size="4 * 1024 * 1024"
								:form-data="{'biz':'temp'}" :header="header" @on-success="uploadSuccess"
								:action="getUploadUrl()" max-count="5">
							</u-upload>
						</u-form-item>
						<view class="font-12 text-FF0000 pl-1 pb-2">图片大小限制不能超过4MB,最多能上传五张图片</view>
						<u-form-item required label-width="180" label="服务价格(元)" prop="servicePrice">
							<u-input v-model="form.servicePrice" input-align="right" />
						</u-form-item>
						<!-- <u-form-item required label-width="180" label="服务流程" prop="serviceFlow">
							<u-input v-model="form.serviceFlow" input-align="right" />
						</u-form-item>
						<u-form-item required label-width="180" label="售后服务" prop="serviceInform">
							<u-input v-model="form.serviceInform" input-align="right" />
						</u-form-item> -->

						<view style=" background-color:#EFEDE9;">
							<view class="pl-2 pr-2 font-14 lineHight-40 font-weight-bold">我的信息</view>
						</view>
						<u-form-item required label-width="180" label="涉农企业" prop="agricultureUserId">
							<u-input :disabled="true" v-model="form.agricultureEnterpriseName" input-align="right" />
						</u-form-item>
						<u-form-item required label-width="180" label="联系方式" prop="phone">
							<u-input :disabled="true" v-model="form.phone" input-align="right" />
						</u-form-item>
						<view style=" background-color:#EFEDE9;">
							<view class="pl-2 pr-2 font-14 lineHight-40 font-weight-bold">订单信息</view>
						</view>
						<u-form-item required label-width="180" label="订单时间" prop="orderTime">
							<uni-calendar ref="calendarl" :start-date="currentDate" :insert="false" :lunar="true"
								@confirm="confirmName" :time-picker="true" />
							<view v-if="!selectedNameDate" class="text-999999 right-1-5 position-absolute"
								@click="openName">
							</view>
							<view class="right-1-5 position-absolute" @click="openName">{{ formattedOrderTime }}</view>
						</u-form-item>
						<u-form-item required label-width="180" label="订单进度" prop="orderSchedule">
							<u-input v-model="form.orderSchedule" input-align="right" />
						</u-form-item>
						<u-form-item required label-width="180" label="订单评论" prop="orderEvaluation">
							<u-input v-model="form.orderEvaluation" input-align="right" />
						</u-form-item>
					</u-form>
				</view>
			</view>
			<ferrButton title="确认新增订单" @click="submit"></ferrButton>
		</scroll-view>
	</view>
</template>

<script>
	import $H from '@/common/free-lib/request.js';
	import {
		getImageUrl
	} from '@/common/free-lib/util.js';
	import ferrButton from "@/components/free-ui/ferr-button.vue";
	import calendar from "@/uni_modules/uni-calendar/components/uni-calendar/uni-calendar.vue"
	export default {
		components: {
			ferrButton,
			calendar
		},
		data() {
			return {
				form: {
					serviceIntroduce: '',
					servicePrice: '',
					serviceFlow: '',
					serviceInform: '',
					serviceName: '',
					upperUserId: '',
					agricultureUserId: '',
					phone: '',
					orderTime: '',
					orderSchedule: '',
					orderEvaluation: '',
					productInformId: '',
					agricultureUserId: '',
					upperEnterpriseName: '',
					serviceIntroductionUrl: '',
				},
				list: {
					userType: 'UPPER_SERVICE',
				},
				value: '',
				valueList: '',
				type: 'select',
				showData: false,
				selectedDate: null,
				selectedNameDate: null,
				actionListCp: [], // 产品名称列表
				showProductName: false, // 控制显示产品名称选项的变量
				valueProductName: '', // 选中的产品名称值
				show: false,
				showList: false,


				// 上游订单
				valueListCp: '',
				actionListCp: [],
				showListCp: false,
				border: true,
				rules: {
					productServeName: [{
						required: true,
						message: '产品/服务名称不能为空',
						trigger: ['change', 'blur'],
					}],
					serviceName: [{
						required: true,
						message: '服务商名称不能为空',
						trigger: ['change', 'blur'],
					}],
					serviceIntroduce: [{
						required: true,
						message: '服务介绍不能为空',
						trigger: ['change', 'blur'],
					}],
					serviceFlow: [{
						required: true,
						message: '服务流程不能为空',
						trigger: ['change', 'blur'],
					}],
					serviceInform: [{
						required: true,
						message: '售后服务不能为空',
						trigger: ['change', 'blur'],
					}],
					orderSchedule: [{
						required: true,
						message: '订单进度不能为空',
						trigger: ['change', 'blur'],
					}],
					orderEvaluation: [{
						required: true,
						message: '订单评论不能为空',
						trigger: ['change', 'blur'],
					}],
					servicePrice: [{
						validator: (rule, value, callback) => {
							if (!value) {
								callback(new Error('预计产量不能为空'));
							} else {
								const reg = /^[0-9]+(\.[0-9]+)?$/; // 允许输入整数和小数
								if (!reg.test(value)) {
									callback(new Error('请输入数字'));
								} else {
									callback();
								}
							}
						},
						trigger: ['change', 'blur'],
					}],
				},
				header: $H.getTokenHeader(),
				valueProductName: '',
				showNatureBusiness: false,
				natureBusinessList: [],
                
				maxCharacters: 200 
			};
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		onLoad(options) {
			const id = options.id;
			this.NewListDetail(id)
			this.NewListD()
		},

		computed: {
			fileList() {
				return Array.isArray(this.form.serviceIntroductionUrl) ? this.form.serviceIntroductionUrl : [];
			},
			formattedOrderTime() {
			    if (!this.form.orderTime) return '';
			    return this.form.orderTime.split(' ')[0];
			},
			wordCount() {
			  // 计算输入框中的字符数
			  return this.form.serviceIntroduce.length;
			}
		},
		created() {
			this.setCurrentDate();
		},
		methods: {
			getUploadUrl(url) {
				return $H.getFullUrl('sys/common/upload');
			},
			uploadSuccess(response, file, ) {
				this.file = file;
			},

			getFullImageUrl(imagePath) {
				return getImageUrl(imagePath);
			},
			showNatureBusinessHandler() {
				this.showNatureBusiness = true;
			},
			selectNatureBusiness(e) {
				this.valueProductName = this.natureBusinessList[e[0]].text;
				this.form.upperUserId = this.natureBusinessList[e[0]].id;
				this.form.productInformId = this.natureBusinessList[e[0]].id
				this.form.upperEnterpriseName = this.natureBusinessList[e[0]].text;
			},
			NewListD() {
				const requestData = {
					...this.list,
				};
				$H.get('/brand/user/selectUserList', requestData, {}).then((res) => {
					this.natureBusinessList = (res.result || []).map((v) => {
						return {
							text: v.enterpriseName,
							id: v.id,
							upperEnterpriseName: v.upperEnterpriseName,
						}
					})
					const target = this.natureBusinessList.find(
						(v) => v.id === this.form.productInformId
					)
					this.valueProductName = target ? target.text : ''
				})
			},

			// 提交 
			submit() {
				let files = this.$refs.uUpload.lists.filter(val => val.progress === 100);

				// Check if no files are uploaded
				if (files.length === 0) {
					this.form.serviceIntroductionUrl = ""; // Set default image URL or empty string
					uni.showToast({
						title: '请上传文件',
						icon: 'none'
					});
					return;
				}

				this.$refs.uForm.validate(valid => {
					if (valid) {
						// Get the uploaded file URLs
						const uploadedFileUrls = files
							.filter(file => file.response?.message)
							.map(file => file.response.message);

						// Concatenate default image URLs with uploaded file URLs
						const allFileUrls = [
							...this.form.serviceIntroductionUrl.map(defaultImage => defaultImage.url),
							...uploadedFileUrls
						].filter(url => url).join(',');

						if (this.form.orderTime) {
							const date = new Date(this.form.orderTime);
							this.form.orderTime =
								`${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} 00:00:00`;
						}

						const requestData = {
							...this.form,
							serviceIntroductionUrl: allFileUrls
						};

						$H.post('/upper/upperMarketOrder/agriculture/editOrder', requestData, {}).then(res => {
							if (res.code === 200) {
								uni.showToast({
									title: res.message || '编辑成功',
									icon: 'success',
									duration: 4000
								});
								setTimeout(() => {
									uni.navigateBack({
										delta: 1
									});
								}, 4000);
							} else {
								uni.showToast({
									title: res.message || '编辑失败',
									icon: 'none'
								});
							}
						}).catch(error => {
							uni.showToast({
								title: "网络错误，请稍后再试",
								icon: 'none'
							});
						});
					} else {
						uni.showToast({
							title: "请完整填写表单",
							icon: 'none'
						});
					}
				});
			},

			openName() {
				this.$refs.calendarl.open();
			},
			confirmName(e) {
				this.selectedNameDate = e.fulldate;
				// 获取当前的日期
				const formattedDate = e.fulldate; // 只使用日期部分
				this.form.orderTime = formattedDate;

			},
			setCurrentDate() {
				const now = new Date();
				const year = now.getFullYear();
				const month = (now.getMonth() + 1).toString().padStart(2, '0'); // 月份补齐两位数
				const day = now.getDate().toString().padStart(2, '0'); // 日期补齐两位数
				this.currentDate = `${year}-${month}-${day}`;
			},

			NewListDetail(id) {
				$H.get('/upper/upperMarketOrder/queryById', {
					id: id
				}, {}).then(res => {
					this.form = res.result
					if (res.result.serviceIntroductionUrl) {
						this.form.serviceIntroductionUrl = res.result.serviceIntroductionUrl.split(',').map(url =>
							({
								url: this.getFullImageUrl(url)
							}));
					} else {
						this.form.serviceIntroductionUrl = [];
					}
				}).catch(error => {
					uni.showToast({
						title: "网络错误，请稍后再试",
						icon: 'none'
					});
				});
			},

		},
	};
</script>

<style>
	.tab-container {
		display: flex;
		flex-direction: column;
	}

	.tab-list {
		display: flex;
		justify-content: space-between;
	}

	.tab-list view {

		cursor: pointer;
	}

	.tot {
		border: 2px solid #cecece;
		border-radius: 100%;
		width: 18px;
		height: 18px;
	}

	.active {
		width: 10px;
		height: 10px;
		border-radius: 100%;
		left: 2px;
		position: relative;
		border: 1px solid #78AB06;
		background-color: #78AB06;


	}

	.tab-content {
		margin-top: 20px;
	}
</style>